<template>
  <container>
    <el-space wrap>
      <el-input v-model="userParams.userName" placeholder="请输入用户名称"></el-input>
      <el-input v-model="userParams.phone" placeholder="请输入用户手机号"></el-input>
      <el-button :icon="Refresh" type="success" @click="refresh">刷新</el-button>
      <el-button :icon="Search" type="primary" @click="_getUserList">搜索</el-button>
    </el-space>
    <div class="mt-20 mb-20">
      <el-button type="primary" :icon="Plus" @click="showAddUserDialog = true">添加用户</el-button>
      <el-button type="danger" plain :icon="Delete" :disabled="checkList.length <= 0">批量删除</el-button>
    </div>
    <el-table v-loading="loading" :data="userList" border @select-row="selectChange">
      <el-table-column type="selection" align="center" />
      <el-table-column label="用户姓名" fixed width="180">
        <template #default="{ row }">
          <div class="flex align-center">
            <el-avatar :src="row.avatar" :size="32" />
            <span class="ml-10">{{ row.name }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="账号" prop="account" width="150" />
      <el-table-column label="角色" width="150">
        <template #default="{ row }">
          <el-tag type="primary" plain border>{{ roleList.find((v) => v.id === row.roles)?.name }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="手机号" prop="phone" width="200" />
      <el-table-column label="是否在线" width="120">
        <template #default="{ row }">
          <dots :color="row.online === '1' ? '#22c55e' : '#ef4444'" style="margin-right: 4px" />
          <span> {{ row.online === '1' ? '在线' : '离线' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" min-width="240" />
      <el-table-column label="操作" fixed="right" align="center" width="200">
        <template #default="{ row }">
          <el-button type="primary" size="small" text @click="_editUser(row)">编辑</el-button>
          <el-button type="danger" size="small" text @click="_deleteUser(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-model:limit="userParams.pageSize"
      v-model:page="userParams.pages"
      :total="total"
      @pagination="_getUserList"></pagination>

    <el-dialog v-model="showAddUserDialog" :header="`${isEdit ? '修改' : '新增'}用户`" width="700px">
      <div class="dialog-content">
        <el-form :model="userForm" ref="formRef" :rules="rules">
          <el-form-item label="账号" prop="account">
            <el-input v-model="userForm.account" placeholder="请输入用户账号" />
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="userForm.name" placeholder="请输入用户姓名" />
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="userForm.phone" placeholder="请输入用户手机号" />
          </el-form-item>
          <el-form-item label="角色" prop="name">
            <el-select v-model="userForm.roles" placeholder="请选择用户姓名">
              <el-option v-for="role in roleList" :value="role.id" :label="role.name" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button plain @click="cancel">取消</el-button>
        <el-button type="primary" @click="confirm">{{ isEdit ? '确认修改' : '新增' }}</el-button>
      </template>
    </el-dialog>
  </container>
</template>

<script setup lang="ts">
import { getUserList, addUser, deleteUser, updateUser, getRoles } from '@/mocks/system';
import { onMounted, ref } from 'vue';
import { Delete, Plus, Refresh, Search } from '@icon-park/vue-next';
import dots from '@/components/dots/main.vue';
import container from '@/components/container';
import { ElMessageBox, ElMessage } from 'element-plus';

const { confirm: $confirm } = ElMessageBox;

const roleList = ref([]);
const userList = ref<any[][]>([]);
const checkList = ref([]);
const total = ref(0);
const userParams = ref({
  pageSize: 10,
  pages: 1,
  userName: '',
  phone: ''
});
const loading = ref(false);
const showAddUserDialog = ref(false);
const isEdit = ref(false);
const formRef = ref();
const userForm = ref({
  name: '',
  account: '',
  roles: '',
  phone: ''
});
const rules = ref({
  name: { required: true, message: '请输入姓名', trigger: 'blur' },
  account: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
  age: { type: 'number', required: true, message: '请输入年龄', trigger: 'blur' },
  phone: { required: true, message: '请输入手机号', trigger: 'blur' }
});

function _getUserList() {
  loading.value = true;
  getUserList(userParams.value).then((res) => {
    userList.value = res.data;
    total.value = res.total;
    loading.value = false;
  });
}

function selectChange(row) {
  checkList.value = row;
}

function _deleteUser(row) {
  $confirm('确定要删除该用户吗？', 'warning').then((_) => {
    deleteUser(row.id).then((_) => {
      ElMessage.success('已删除该用户');
      refresh();
    });
  });
}

function _editUser(row) {
  Object.keys(userForm.value).forEach((key) => {
    userForm.value[key] = row[key];
  });
  userForm.value['id'] = row.id;
  isEdit.value = true;
  showAddUserDialog.value = true;
}

function cancel() {
  userForm.value = {
    name: '',
    account: '',
    roles: '',
    phone: ''
  };
  showAddUserDialog.value = false;
}

function confirm() {
  formRef.value.validate((vald: boolean) => {
    if (!vald) return;
    if (isEdit.value) {
      _updateUser();
    } else {
      _addUser();
    }
  });
}

function _addUser() {
  addUser(userForm.value).then((_) => {
    showAddUserDialog.value = false;
    $message.success?.('添加用户成功');
    refresh();
  });
}

function _updateUser() {
  updateUser(userForm.value).then((_) => {
    showAddUserDialog.value = false;
    $message.success?.('修改用户信息成功');
    refresh();
  });
}

function refresh() {
  userParams.value.pages = 1;
  userParams.value.phone = '';
  userParams.value.userName = '';
  _getUserList();
}

function _getRoles() {
  getRoles({ pages: 1, pageSize: 100 }).then((res) => {
    roleList.value = res.data;
  });
}

onMounted(() => {
  _getRoles();
  _getUserList();
});
</script>

<style scoped lang="scss">
.dialog-content {
  padding: 10px;
}
</style>
